package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.aliyuncs.exceptions.ClientException;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisMessageConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.Order;
import com.itheima.service.OrderService;
import com.itheima.util.SMSUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import java.util.Map;

/**
 * 体检预约
 */
@RestController
@RequestMapping("/order")
public class OrderController {

    @Reference
    private OrderService orderService;
    @Autowired
    private JedisPool jedisPool;

    //体检预约
    @RequestMapping("/submit")
    public Result submitOrder(@RequestBody Map map) {
        //获得用户输入的手机号
        String telephone = (String) map.get("telephone");
        //根据手机号到redis中查到给用户生成的验证码
        String validateCode_redis = jedisPool.getResource().get(telephone + RedisMessageConstant.SENDTYPE_ORDER);
        //获得用户填写的验证码
        String validateCode = (String) map.get("validateCode");
        if (validateCode != null && validateCode_redis != null && validateCode.equals(validateCode_redis)) {
            //说明用户填写的验证码正确
            map.put("orderType", Order.ORDERTYPE_WEIXIN);//预约类型：微信预约
            Result result = null;
            try {
                result = orderService.order(map);
            } catch (Exception e) {
                //预约失败
                e.printStackTrace();
                return new Result(false, "预约失败");
            }
            if (result.isFlag()) {
                //预约成功
                try {
                    //发送短信提醒用户预约成功并告知用户体检时间
                    SMSUtils.sendShortMessage(SMSUtils.ORDER_NOTICE, telephone, (String) map.get("orderDate"));
                } catch (ClientException e) {
                    e.printStackTrace();
                }
            }
            return result;

        } else {
            //验证码不正确，提示用户
            return new Result(false, MessageConstant.VALIDATECODE_ERROR);
        }
    }

    //根据id查询预约信息，包括套餐信息和会员信息
    @RequestMapping("/findById")
    public Result findById(Integer id) {
        try {
            Map map = orderService.findById(id);
            return new Result(true, MessageConstant.QUERY_ORDER_SUCCESS, map);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.QUERY_ORDER_FAIL);
        }
    }

}
